import { history, useLocation, useParams } from 'umi';

const modeConfig = {
  isAdd: '/add',
  isModify: '/modify',
  isRead: '/read',
};

type ModeConfig = Partial<typeof modeConfig>;

/**
 * 详情页面统一逻辑判断
 * @returns
 */
const useDetailType = <T extends { [K in keyof T]?: string }>(config = {} as ModeConfig) => {
  const { pathname } = useLocation();
  const params = useParams<T>();

  const _config = { ...modeConfig, ...config };

  const isAdd = pathname.includes(_config.isAdd);
  const isModify = pathname.includes(_config.isModify);
  const isRead = pathname.includes(_config.isRead);

  const goBack = () => history.goBack();
  const goReplace = (url: string) => url && history.replace(url);
  const goto = (url: string) => url && history.push(url);

  return {
    // 新增
    isAdd,
    // 编辑
    isModify,
    // 详情
    isRead,
    // 页面参数
    params,
    // 页面路径
    pathname,
    // umi history 对象
    history,
    goBack,
    goReplace,
    goto,
  };
};

export default useDetailType;
